package cn.lbaicai.utils;

import java.util.Random;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import cn.lbaicai.entity.Emp;
import cn.lbaicai.entity.User;

public class PasswordHelper {
	  private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	  private String algorithmName = "md5";
	  private final int hashIterations = 2;
	  public Emp encryptPassword(Emp user) {
	        // User对象包含最基本的字段Username和Password
	        //user.setSalt(randomNumberGenerator.nextBytes().toHex());
		  	user.setSalt(getItemName(6));
	        // 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据，散列过程使用了盐
	        String newPassword = new SimpleHash(algorithmName, user.getPassword(),
	                ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();
	        user.setPassword(newPassword);
	        return user;
	  }
	  public User encryptPassword(User user) {
	        // User对象包含最基本的字段Username和Password
	        //user.setSalt(randomNumberGenerator.nextBytes().toHex());
		  	user.setSalt(getItemName(6));
	        // 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据，散列过程使用了盐
	        String newPassword = new SimpleHash(algorithmName, user.getPassword(),
	                ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();
	        user.setPassword(newPassword);
	        return user;
	  }
	  /**
	     * 生产ItemName随机函数
	     * @param length
	     * @return
	     */
	  public static String getItemName( int length ){
	        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	        Random random = new Random();
	        StringBuffer sb = new StringBuffer();
	        for ( int i = 0; i < length; i++ )
	        {
	            int number = random.nextInt( base.length() );
	            sb.append( base.charAt( number ) );
	        }
	        return sb.toString();
	    }
}
